const app = getApp()

import axios from '../../utils/axios'

Page({

  data: {
    contactList: [], // 用户收货地址list
  },

  onLoad: function (options) {

  },

  onShow: function () {
    this.selectContactList()

  },

  // 设为默认地址
  defaultAddress: function (e) {

    let contactId = e.currentTarget.dataset.contactid

    axios('/user/defaultContact', {
      contact_id: contactId,
      common: 1
    }).then(res => {
      if (res.data.resultcode == 1) {
        this.selectContactList()
      }
    })

  },

  // 跳转新增地址
  checkAddress: function () {
    wx.navigateTo({
      url: '/pages/newAddress/newAddress',
    })
  },

  // 选择地址
  pitchAddress: function (e) {
    let contactId = e.currentTarget.dataset.contactid

    let list = this.data.contactList

    for (let i = 0; i < list.length; i++) {
      if (list[i].id == contactId) {

        app.globalData.showAddress = true

        wx.setStorageSync('address', list[i])

        wx.navigateBack({
          delta: 1
        })

        break;
      }
    }
  },

  // 编辑地址
  editAddress: function (e) {
    wx.navigateTo({
      url: '/pages/newAddress/newAddress?contactId=' + e.currentTarget.dataset.contactid,
    })
  },

  // 删除地址
  deleteAddress: function (e) {

    const self = this;
    let contactId = e.currentTarget.dataset.contactid

    wx.showModal({
      title: '温馨提示',
      content: '确定删除该地址吗?',
      cancelText: '取消',
      confirmText: '确定',
      success(res) {
        if (res.confirm) {
          self.sureDelete(contactId);
        }
      }
    })

  },

  // 确认删除
  sureDelete: function (contactId) {
    axios('/user/removeContact', {
      contact_id: contactId
    }).then(res => {
      console.log(res)
      if (res.data.resultcode == 1) {
        this.selectContactList()
        wx.showToast({
          title: '删除成功',
          icon: 'none',
          duration: 1200
        });
      }
    })
  },

  // 查询用户收货地址
  selectContactList: function () {

    axios('/user/contactList').then(res => {
      console.log(res)
      if (res.data.resultcode == 1) {
        this.setData({
          contactList: res.data.result
        })
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})